//
//  KLMDeviceSettingController.swift
//  KLM_GN
//
//  Created by Nic on 2025/2/27.
//

import UIKit
import nRFMeshProvision

class KLMDeviceSettingController: KLMBaseRowController {
    
    let deviceInfo: KLMHomeDevice
    private var configModel: KLMRKDeviceConfig?
    private var isVersionFirst = true
    
    init(info: KLMHomeDevice) {
        deviceInfo = info
        super.init(nibName: nil, bundle: nil)
    }

    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        showEmptyState()
        checkDeviceInfo()
        
        checkConfigDevice()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        checkConfigDevice()
    }
    // MARK: - 查询设备参数
    private func checkConfigDevice() {
        KLMRequest.queryRKDeviceProfile(meshId: deviceInfo.meshId, uuid: deviceInfo.uuid) { response in
            self.hideEmptyState()
            
            guard let model: KLMRKDeviceConfig = response as? KLMRKDeviceConfig else {return }
            self.configModel = model
            self.rowItems = KLMRowItem.deviceInfoSettingItems(info: self.deviceInfo, config: model)
            
//            self.showUpdateView()
            self.tableView.reloadData()
            if !model.isOnline {
                KLMAlertController.showAlertWithTitle(title: KLMLocalizable.LANGLOC("Device Offline"), message: nil)
            }
        } failure: { error in
            self.hideEmptyState()
        }
    }
    // MARK: - 删除设备
    func tapDelete() {
        print("tapDelete")
//        if configModel?.online == 0 {
//            SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("Device Offline"))
//            return
//        }
        let model = KLMHomeManager.currentNode
        KLMHomeMesh.canEditMesh { [weak self] in
            guard let self = self else {return }
            //弹出提示框
            let warnAlert = UIAlertController(title: KLMLocalizable.LANGLOC("Remove Device"),
                                              message: KLMLocalizable.LANGLOC("Please manually reset the fixture, and re-add it through the app"),
                                              preferredStyle: .alert)
            let warnresetAction = UIAlertAction(title: KLMLocalizable.LANGLOC("Remove"), style: .default) { _ in
                if model.isRK {
                    SVProgressHUD.show()
                    ///RK设备设置复位，先删除服务器(蓝牙也会复位)
                    KLMRequest.homeDeleteDevice(meshId: self.deviceInfo.meshId, uuid: self.deviceInfo.uuid) { response in
                        SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
                        NotificationCenter.default.post(name: .deviceReset, object: nil)
                        self.navigationController?.popViewController(animated: true)
                    } failure: { error in
                        KLMHttpShowError(error)
                    }
                    return
                }
                
                ///连接节点
                SVProgressHUD.show()
                KLMConnectManager.shared.connectToNode(node: model) { [weak self] in
                    guard let self = self else { return }
                    //连接上，重置设备
                    KLMSmartNode.sharedInstacnce.delegate = self
                    KLMSmartNode.sharedInstacnce.resetNode(node: model)
                    
                } failure: {
                    //连接不上，直接删除设备
                    KLMRequest.homeDeleteDevice(meshId: self.deviceInfo.meshId, uuid: self.deviceInfo.uuid) { response in
                        SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
                        NotificationCenter.default.post(name: .deviceReset, object: nil)
                        self.navigationController?.popViewController(animated: true)
                    } failure: { error in
                        KLMHttpShowError(error)
                    }
                }
            }
            let warncancelAction = UIAlertAction(title: KLMLocalizable.LANGLOC("Cancel"), style: .cancel)
            warnAlert.addAction(warnresetAction)
            warnAlert.addAction(warncancelAction)
            self.present(warnAlert, animated: true)
        } failure: {
            
        }
    }
    // MARK: - 设备重命名
    func tapToRenameDevice(_ item: KLMRowItem) {
        KLMHomeMesh.canEditMesh{ [weak self] in
            guard let self = self else {return }
            
            let vc = KLMBaseModalController(type: .rename, operTitle: KLMLocalizable.LANGLOC("Rename"), textFieldTip: item.subTitle, cancelBlock: {
                
            }, confirmBlock: { name, type in
                if type != .rename { return }
                
                if KLMSmartGroup.allNodes().contains(where: {$0.name == name }) {
                    SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("The name already exists"))
                    return
                }
                //修改名称
                SVProgressHUD.show()
                KLMRequest.updateDeviceInfo(meshId: self.deviceInfo.meshId, uuid: self.deviceInfo.uuid, deviceName: name) { response in
                    SVProgressHUD.dismiss()
                    //发送通知更新首页
                    NotificationCenter.default.post(name: .deviceNameUpdate, object: nil)
                    KLMHomeManager.currentNode.name = name
                    self.rowItems[0][0].subTitle = name
                    
                    self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .left)
                } failure: { error in
                    KLMHttpShowError(error)
                }
            })
            modalVc(vc: vc)
        } failure: { }
    }
    // MARK: - 设备更新位置
    func tapToJoinRoom() {
        let roomVc = KLMRoomListController(homeId: deviceInfo.meshId, operType: .move)
        roomVc.titleText = "将设备移动至"
        roomVc.popRefreshBlock = { [weak self] name, type, roomCount in
            guard let self = self else { return }
            self.rowItems[0][1].subTitle = name
            self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .left)
        }
        navigationController?.pushViewController(roomVc, animated: true)
    }
    
    private func checkDeviceInfo() {
//        SVProgressHUD.show()
//        KLMService.selectDevice(uuid: KLMHomeManager.currentNode.nodeuuidString) { response in
//            SVProgressHUD.dismiss()
//            guard let model = response as? KLMDeviceInfo else { return }
//            self.deviceInfo = model
//            if model.productKey == nil {
//                SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("Data acquisition failed, please reset and try again"))
//            } else {
//                self.startMQTT()
//            }
//        } failure: { error in
//            KLMHttpShowError(error)
//        }
    }
    ///连接RK设备 - 查看图像还有OTA
    private func startMQTT() {
//        KLMMQTTManager.shared.startConnection(productKey: deviceInfo.productKey, deviceKey: deviceInfo.deviceKey)
    }
    private func showUpdateView() {
        guard let config = configModel else {
            return
        }
        
        if !config.isOnline {
            return
        }
        
        guard let currentVersion = config.version,
              let newestVersion = config.destVersion else {
            
            return
        }
        
        if isVersionFirst {
            isVersionFirst = false
            
            KLMTool.checkBluetoothVersion(newestVersion: newestVersion, bleversion: currentVersion, EnMessage: config.firmwareDesc ?? "", CNMessage: config.firmwareDesc ?? "", viewController: self) { [weak self] in
                guard let self = self else { return }
                
//                let vc = KLMRKDFUViewController()
//                vc.deviceInfo = deviceInfo
//                vc.destVersion = newestVersion
//                navigationController?.pushViewController(vc, animated: true)
                
            } cancel: { [weak self] in
                guard let self = self else { return }
                //                if bleData.isForceUpdate {
                //                    self.navigationController?.popViewController(animated: true)
                //                }
            } noNeedUpdate: { //不需要升级
                
            }
        }
    }
    // MARK: - tableViewCell点击事件
    override func tableViewDidSelect(item: KLMRowItem, at: IndexPath, on: UITableView) {
        switch item.type {
        case .deleteDevice:
            tapDelete()
        case .deviceName:
            tapToRenameDevice(item)
        case .deviceLocation:
            tapToJoinRoom()
        case .AIMode:
            let aiVc = KLMAIModeController(device: deviceInfo, deviceConfig: configModel!)
            aiVc.titleText = item.title
            navigationController?.pushViewController(aiVc, animated: true)
        case .sceneMode:
            let sceneVc = KLMSceneModeController(device: deviceInfo, deviceConfig: configModel!)
            sceneVc.titleText = item.title
            navigationController?.pushViewController(sceneVc, animated: true)
        default:
            break
        }
    }
    
    override func rowItemCellToggleOn(cell: KLMBaseRowItemCell, index: IndexPath, on tableView: UITableView) {
        /*
         1.AI模式与情景模式冲突，只能二选一；
         2.恒照度模式与AI模式&情景模式冲突，打开恒照度模式则只能关闭AI模式与情景模式
         */
        var item = rowItems[index.section][index.row]
        item.isOn = !item.isOn
        KLMHomeMesh.canEditMesh {[weak self] in
            guard let self = self else { return }
            // 如果打开，且不是入座感应模式
            if item.isOn, item.type != .seatingInduction {
                let situationalModeEnable = item.type == .sceneMode ? 1: 0
                let constantLightEnable = item.type == .constantIlluminanceMode ? 1: 0
                let sceneSwitch = item.type == .AIMode ? 1: 0
                
                performConfigDeviceRequest(configDict: [
                    "situationalModeEnable" : situationalModeEnable,
                    "constantLightEnable" : constantLightEnable,
                    "sceneSwitch" : sceneSwitch
                ]) {
                    switch item.type {
                    case .constantIlluminanceMode:
                        if let aiIndex = self.rowItems[index.section].firstIndex(where: { $0.type == .AIMode && $0.isOn }) {
                            self.rowItems[index.section][aiIndex].isOn = false
                        }
                        if let sceneIndex = self.rowItems[index.section].firstIndex(where: { $0.type == .sceneMode && $0.isOn }) {
                            self.rowItems[index.section][sceneIndex].isOn = false
                        }
                    case .AIMode:
                        if let constantIndex = self.rowItems[index.section].firstIndex(where: { $0.type == .constantIlluminanceMode && $0.isOn }) {
                            self.rowItems[index.section][constantIndex].isOn = false
                        }
                        if let sceneIndex = self.rowItems[index.section].firstIndex(where: { $0.type == .sceneMode && $0.isOn }) {
                            self.rowItems[index.section][sceneIndex].isOn = false
                        }
                    case .sceneMode:
                        if let constantIndex = self.rowItems[index.section].firstIndex(where: { $0.type == .constantIlluminanceMode && $0.isOn }) {
                            self.rowItems[index.section][constantIndex].isOn = false
                        }
                        if let aiIndex = self.rowItems[index.section].firstIndex(where: { $0.type == .AIMode && $0.isOn }) {
                            self.rowItems[index.section][aiIndex].isOn = false
                        }
                    default:
                        break
                    }
                    
                    self.rowItems[index.section][index.row] = item
                    self.tableView.reloadSections(IndexSet.init(integer: 0), with: .fade)
                }
            } else {
                let enable = item.isOn == true ? 1 : 0
                let typeKeyDict: [RowItemType: String] = [
                    .seatingInduction: "seatInductionEnable",
                    .constantIlluminanceMode: "constantLightEnable",
                    .sceneMode: "situationalModeEnable",
                    .AIMode: "sceneSwitch"
                ]
                let key = typeKeyDict[item.type] ?? "sceneSwitch"
                SVProgressHUD.show()
                performConfigDeviceRequest(configDict: [key: enable]) {
                    self.rowItems[index.section][index.row] = item
                    self.tableView.reloadSections(IndexSet.init(integer: 0), with: .fade)
                }
            }
        } failure: { }
    }
    private func performConfigDeviceRequest(configDict: [String: Any], completion: @escaping () -> Void) {
        SVProgressHUD.show()
        KLMRequest.configRKDeviceProfile(meshId: deviceInfo.meshId, uuid: deviceInfo.uuid, configDict: configDict) {reponse in
            SVProgressHUD.dismiss()
            completion()
        } failure: { error in
            SVProgressHUD.dismiss()
            KLMHttpShowError(error)
        }
    }
}

extension KLMDeviceSettingController: KLMSmartNodeDelegate {
    
    func smartNodeDidResetNode(_ manager: KLMSmartNode) {
        
        ///RK设备设置复位，先删除服务器(蓝牙也会复位)
        KLMRequest.homeDeleteDevice(meshId: deviceInfo.meshId, uuid: manager.currentNode!.nodeuuidString) { response in
            SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
            NotificationCenter.default.post(name: .deviceReset, object: nil)
            self.navigationController?.popToRootViewController(animated: true)
        } failure: { error in
            KLMHttpShowError(error)
        }
    }
    
    func smartNode(_ manager: KLMSmartNode, didfailure error: MessageError?) {
        
        KLMShowError(error)
    }
}
